<template>
  <ion-page>
    <ion-header :translucent="true">
      <ion-toolbar>
        <ion-buttons slot="start">
          <ion-back-button default-href="/tabs/profile"></ion-back-button>
        </ion-buttons>
        <ion-title>我的房源</ion-title>
        <ion-buttons slot="end">
          <ion-button @click="goToPublishProperty" fill="clear">
            <ion-icon :icon="addOutline"></ion-icon>
          </ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>

    <ion-content :fullscreen="true">
      <!-- 筛选标签 -->
      <div class="filter-tabs">
        <ion-segment v-model="selectedFilter" @ionChange="onFilterChange">
          <ion-segment-button value="all">
            <ion-label>全部</ion-label>
          </ion-segment-button>
          <ion-segment-button value="available">
            <ion-label>未出租</ion-label>
          </ion-segment-button>
          <ion-segment-button value="rented">
            <ion-label>已出租</ion-label>
          </ion-segment-button>
        </ion-segment>
      </div>

      <!-- 统计信息 -->
      <div class="stats-bar">
        <div class="stat-item">
          <span class="stat-number">{{ stats.total }}</span>
          <span class="stat-label">总房源</span>
        </div>
        <div class="stat-item">
          <span class="stat-number">{{ stats.available }}</span>
          <span class="stat-label">未出租</span>
        </div>
        <div class="stat-item">
          <span class="stat-number">{{ stats.rented }}</span>
          <span class="stat-label">已出租</span>
        </div>
      </div>

      <!-- 房源列表 -->
      <div class="properties-container" v-if="filteredProperties.length > 0">
        <ion-card 
          v-for="property in filteredProperties" 
          :key="property.id" 
          class="property-card"
        >
          <ion-card-content>
            <!-- 房源状态标签 -->
            <div class="property-status">
              <ion-chip 
                :color="property.status === 'available' ? 'success' : 'medium'"
                size="small"
              >
                {{ property.status === 'available' ? '未出租' : '已出租' }}
              </ion-chip>
            </div>

            <!-- 房源信息 -->
            <div class="property-info">
              <div class="property-header">
                <h3 class="property-title">{{ property.title }}</h3>
                <div class="property-price">¥{{ property.price }}/月</div>
              </div>
              
              <div class="property-details">
                <p class="property-address">
                  <ion-icon :icon="locationOutline" size="small"></ion-icon>
                  {{ property.address }}
                </p>
                
                <div class="property-specs">
                  <span class="spec-item">{{ property.rooms }}室</span>
                  <span class="spec-item">{{ property.bathrooms }}卫</span>
                  <span class="spec-item">{{ property.area }}㎡</span>
                </div>
              </div>

              <!-- 联系信息 -->
              <div class="contact-info">
                <div class="contact-item">
                  <span class="contact-label">房东：</span>
                  <span class="contact-value">{{ property.contactName }}</span>
                </div>
                <div class="contact-item">
                  <span class="contact-label">联系方式：</span>
                  <span class="contact-value">{{ formatPhone(property.contactPhone) }}</span>
                </div>
              </div>

              <!-- 发布时间 -->
              <div class="publish-info">
                <span class="publish-time">发布时间：{{ formatDate(property.publishDate) }}</span>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="property-actions">
              <ion-button 
                fill="outline" 
                size="small" 
                @click="viewDetails(property)"
              >
                详情
              </ion-button>
              <ion-button 
                fill="outline" 
                size="small" 
                @click="editProperty(property)"
              >
                编辑
              </ion-button>
              <ion-button 
                fill="outline" 
                size="small" 
                @click="togglePropertyStatus(property)"
                :color="property.status === 'available' ? 'medium' : 'success'"
              >
                {{ property.status === 'available' ? '下架' : '上架' }}
              </ion-button>
              <ion-button 
                fill="clear" 
                size="small" 
                color="danger"
                @click="deleteProperty(property)"
              >
                删除
              </ion-button>
            </div>
          </ion-card-content>
        </ion-card>
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-else>
        <ion-icon :icon="homeOutline" size="large" color="medium"></ion-icon>
        <h3>暂无房源</h3>
        <p v-if="selectedFilter === 'all'">您还没有发布任何房源</p>
        <p v-else-if="selectedFilter === 'available'">暂无未出租房源</p>
        <p v-else>暂无已出租房源</p>
        <ion-button @click="goToPublishProperty" fill="outline" v-if="selectedFilter === 'all'">
          立即发布房源
        </ion-button>
      </div>
    </ion-content>
  </ion-page>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import {
  IonPage,
  IonHeader,
  IonToolbar,
  IonTitle,
  IonContent,
  IonButtons,
  IonButton,
  IonBackButton,
  IonIcon,
  IonSegment,
  IonSegmentButton,
  IonLabel,
  IonCard,
  IonCardContent,
  IonChip,
  alertController,
  toastController
} from '@ionic/vue'
import {
  addOutline,
  homeOutline,
  locationOutline
} from 'ionicons/icons'
import { useUserStore } from '@/stores/user'
import { usePropertyStore } from '@/stores/property'
import type { Property } from '@/stores/property'

const router = useRouter()
const userStore = useUserStore()
const propertyStore = usePropertyStore()

// 筛选状态
const selectedFilter = ref('all')

// 我的房源列表
const myProperties = computed(() => {
  if (!userStore.user?.id) return []
  return propertyStore.getPropertiesByLandlord(userStore.user.id.toString())
})

// 筛选后的房源列表
const filteredProperties = computed(() => {
  if (selectedFilter.value === 'all') {
    return myProperties.value
  }
  return myProperties.value.filter(property => property.status === selectedFilter.value)
})

// 统计信息
const stats = computed(() => {
  const total = myProperties.value.length
  const available = myProperties.value.filter(p => p.status === 'available').length
  const rented = myProperties.value.filter(p => p.status === 'rented').length
  
  return { total, available, rented }
})

// 筛选变化处理
const onFilterChange = (event: any) => {
  selectedFilter.value = event.detail.value
}

// 格式化手机号
const formatPhone = (phone: string) => {
  if (phone.length === 11) {
    return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')
  }
  return phone
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 跳转到发布房源页面
const goToPublishProperty = () => {
  router.push('/publish-property')
}

// 查看房源详情
const viewDetails = (property: Property) => {
  console.log('查看房源详情:', property)
  // TODO: 实现房源详情页面
}

// 编辑房源
const editProperty = (property: Property) => {
  console.log('编辑房源:', property)
  // TODO: 实现房源编辑功能
}

// 切换房源状态
const togglePropertyStatus = async (property: Property) => {
  const newStatus = property.status === 'available' ? 'rented' : 'available'
  const statusText = newStatus === 'available' ? '上架' : '下架'
  
  const alert = await alertController.create({
    header: '确认操作',
    message: `确定要${statusText}这个房源吗？`,
    buttons: [
      {
        text: '取消',
        role: 'cancel'
      },
      {
        text: '确定',
        handler: () => {
          propertyStore.updateProperty(property.id, { status: newStatus })
          
          toastController.create({
            message: `房源已${statusText}`,
            duration: 2000,
            color: 'success',
            position: 'top'
          }).then(toast => toast.present())
        }
      }
    ]
  })
  await alert.present()
}

// 删除房源
const deleteProperty = async (property: Property) => {
  const alert = await alertController.create({
    header: '确认删除',
    message: '确定要删除这个房源吗？删除后无法恢复。',
    buttons: [
      {
        text: '取消',
        role: 'cancel'
      },
      {
        text: '删除',
        role: 'destructive',
        handler: () => {
          propertyStore.deleteProperty(property.id)
          
          toastController.create({
            message: '房源已删除',
            duration: 2000,
            color: 'success',
            position: 'top'
          }).then(toast => toast.present())
        }
      }
    ]
  })
  await alert.present()
}
</script>

<style scoped>
.filter-tabs {
  padding: 16px;
  background: white;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.stats-bar {
  display: flex;
  justify-content: space-around;
  padding: 16px;
  background: white;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.stat-number {
  font-size: 20px;
  font-weight: bold;
  color: var(--ion-color-primary);
}

.stat-label {
  font-size: 12px;
  color: var(--ion-color-medium);
}

.properties-container {
  padding: 16px;
}

.property-card {
  margin-bottom: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.property-status {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 12px;
}

.property-info {
  margin-bottom: 16px;
}

.property-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.property-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--ion-color-dark);
  flex: 1;
  margin-right: 12px;
}

.property-price {
  font-size: 18px;
  font-weight: bold;
  color: var(--ion-color-danger);
  white-space: nowrap;
}

.property-details {
  margin-bottom: 12px;
}

.property-address {
  display: flex;
  align-items: center;
  gap: 4px;
  margin: 0 0 8px 0;
  color: var(--ion-color-medium);
  font-size: 14px;
}

.property-specs {
  display: flex;
  gap: 12px;
}

.spec-item {
  font-size: 14px;
  color: var(--ion-color-dark);
  background: rgba(79, 172, 254, 0.1);
  padding: 4px 8px;
  border-radius: 4px;
}

.contact-info {
  background: rgba(0, 0, 0, 0.02);
  padding: 12px;
  border-radius: 8px;
  margin-bottom: 8px;
}

.contact-item {
  display: flex;
  margin-bottom: 4px;
}

.contact-item:last-child {
  margin-bottom: 0;
}

.contact-label {
  font-size: 14px;
  color: var(--ion-color-medium);
  min-width: 80px;
}

.contact-value {
  font-size: 14px;
  color: var(--ion-color-dark);
}

.publish-info {
  text-align: right;
}

.publish-time {
  font-size: 12px;
  color: var(--ion-color-medium);
}

.property-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  flex-wrap: wrap;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-state ion-icon {
  margin-bottom: 16px;
}

.empty-state h3 {
  margin: 0 0 8px 0;
  color: var(--ion-color-dark);
}

.empty-state p {
  margin: 0 0 20px 0;
  color: var(--ion-color-medium);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .property-actions {
    justify-content: center;
  }

  .property-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .property-price {
    margin-top: 8px;
  }
}
</style>
